package com.serkol.config;




import com.alibaba.fastjson2.JSONObject;
import com.serkol.ams.bean.WsResult;
import jakarta.annotation.PostConstruct;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;


import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/ws/device/{uuid}")
@Component
public class WebSocketDeviceServer implements InitializingBean {


    private static final Logger log = LoggerFactory.getLogger(WebSocketDeviceServer.class);
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    // private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
    private static final Map<String, Session> arraySetMap = new HashMap<>();

    @PostConstruct
    public void init() {

        System.out.println("websocket 加载");
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("uuid") String uuid) {

        session.getUserProperties().put("sessionkey", uuid);
        setSessions(uuid, session);
        System.out.println(uuid);
        int cnt = OnlineCount.incrementAndGet(); // 在线数加1
        log.info("有连接加入，当前连接数为：{}", arraySetMap.size());
        //  sendMessage(session, save);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        String pkname = (String) session.getUserProperties().get("sessionkey");


        arraySetMap.remove(pkname);
        System.out.println("Close:" + pkname);
        //  SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", arraySetMap.size());
    }

    @SneakyThrows
    public void onClose(String sessionkey) {
        Session sessions = getSessions(sessionkey);
        sessions.close();
        arraySetMap.remove(sessionkey);
        System.out.println("Close:" + sessionkey);
        //  SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", arraySetMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        sendMessage(session, message);

    }

    public void onMessageAll(String message) {
//String, Session
        for (Map.Entry<String, Session> entry : arraySetMap.entrySet()) {
            String key = entry.getKey();


            Session value = entry.getValue();
            sendMessage(value, message);

        }


    }

    public void onMessageAll(Object message,int type) {

        for (Map.Entry<String, Session> entry : arraySetMap.entrySet()) {
            String key = entry.getKey();

            Session value = entry.getValue();
            sendMessage(value, message,type);

        }


    }

    /**
     * 出现错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        String pkname = (String) session.getUserProperties().get("sessionkey");
        arraySetMap.remove(pkname);
        log.error("发生错误：{}，Session ID： {}", error.getMessage(), session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     *
     * @param session
     * @param message
     */
    public void sendMessage(Session session, Object message) {
        try {
            WsResult result = new WsResult();
            result.setStatus(200);
            result.setData(message);
            String s = JSONObject.toJSONString(result);
            session.getBasicRemote().sendText(s);
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     *
     * @param session
     * @param message
     */
    public void sendMessage(Session session, Object message, int type) {
        try {
            WsResult result = new WsResult();
            result.setStatus(200);
            result.setData(message);
            result.setType(type);

            String s = JSONObject.toJSONString(result);
            log.info("HHHHHHHHHHHHHH", s);
            session.getBasicRemote().sendText(s);
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String packagename, Object message) {
        Session session = getSessions(packagename);
        if (session.isOpen()) {
            sendMessage(session, message, 1);
        }


    }

    /**
     * 指定Session发送消息
     *
     * @param packagename
     * @param message
     * @throws IOException
     */
    public void sendMessage(String packagename, Object message, int type) {
        Session session = null;

        session = getSessions(packagename);


        if (session != null) {
            sendMessage(session, message, type);
        } else {
            log.warn("没有找到你指定ID的会话：{}", packagename);
        }
    }

    public Session getSessions(String pkname) {


        System.out.println("keysss:" + arraySetMap.size());


        if (arraySetMap.containsKey(pkname)) {

            Session session = arraySetMap.get(pkname);
            return session;
        } else {
            return null;
        }


    }

    public boolean isSession(String pkname) {


        System.out.println("keysss:" + arraySetMap.size());


        return arraySetMap.containsKey(pkname);


    }


    public int getCount() {
        int cnt = OnlineCount.get();

        System.out.println("keysss:" + arraySetMap.size());
        System.out.println("getCount:" + cnt);


        return arraySetMap.size();


    }

    public List<String> getDevices() {


        Set<String> integers = arraySetMap.keySet();
        List<String> list = new ArrayList<String>(integers);

        return list;


    }

    private void setSessions(String pkname, Session session) {


        if (!arraySetMap.containsKey(pkname)) {
            arraySetMap.put(pkname, session);

        }


    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }


}